package script;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;

import main.Def;
import main.ErrorDefine;
import main.ErrorException;

import com.sun.tools.javac.Main;

public class ScriptJava
{
	public static HashMap<String, ScriptJava> m_scripts = new HashMap<>();

	private Class<?> m_class;
	private Object m_instance;
	private String m_name;
	
	public static void loadScript(String name) throws ErrorException
	{
		if(!m_scripts.containsKey(name))
		{
			new ScriptJava(name);
		}
	}
	
	private ScriptJava(String name) throws ErrorException
	{
		m_name = name;
		complie();
	}

	private void complie() throws ErrorException
	{
		if(m_scripts.containsKey(m_name))
		{
			throw new ErrorException(ErrorDefine.E_DUPLICATE_SCRIPT_ERR, m_name);
		}
		URLClassLoader loader = null;
		try 
		{
			loader = new URLClassLoader(new URL[]{new File(Def.CLASS_PATH).toURI().toURL()});
			Main.compile(new String[]{Def.CLASS_PATH + m_name + ".java"});
			m_class = loader.loadClass(m_name);
			m_instance = m_class.newInstance();
			m_scripts.put(m_name, this);
		}
		catch(Exception e) 
		{
			String message = m_name + ":   " + e.toString();
			throw new ErrorException(ErrorDefine.E_COMPLIE_SCRIPT_ERR, message);
		}
		finally
		{
			if(loader != null)
			{
				try 
				{
					loader.close();
				} 
				catch(Exception e2)
				{
				}
			}
		}
	}
	
	public void run() throws ErrorException
	{
		try
		{
			m_class.getMethod(Def.SCRIPT_RUN).invoke(m_instance);
		}
		catch(Exception e)
		{
			String message = m_name + ":   " + e.toString();
			throw new ErrorException(ErrorDefine.E_SCRIPT_RUN_ERR, message);
		}
	}
}
